/*
 * @Date: 2022-06-25 11:32:51
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-06-29 15:58:43
 * @FilePath: \taro-music-learn\src\pages\packageA\search\index.tsx
 * @Description: something
 */
import { ScrollView, View } from "@tarojs/components";
import React, { useEffect, useRef, useState } from "react";
import { AtIcon, AtSearchBar, AtTabBar, AtTag } from "taro-ui";
import RankCard from "@/components/RankCard";
import SearchRecommend from "@/components/SearchRecommend";
import { reqSearchSuggest } from "@/api/search";
import { debounce } from "lodash";
import {
  reqHotTopicList,
  reqHotSearchList,
  reqHotSingerList
} from "@/api/search";
import "./index.scss";
import Taro from "@tarojs/taro";
import { ISearchRecommend } from "@/components/SearchRecommend";
export default function index() {
  const [keywords, setKeywords] = useState<string>("");
  const [currentTab, setCurrentTab] = useState(-1);
  const [topicList, setTopicList] = useState([]);
  const [searchList, setSearchList] = useState([]);
  const [singerList, setSingerList] = useState([]);
  const [HistorySearch, setHistorySearch] = useState<Array<string>>([]);
  const [serchRecommend, setSerchRecommend] = useState<
    Pick<ISearchRecommend, "searchInfo">
  >({
    searchInfo: {
      albums: [],
      songs: [],
      playlists: [],
      artists: []
    }
  });
  useEffect(() => {
    fetchHotInfo();
    try {
      setHistorySearch(Taro.getStorageSync("history"));
    } catch (error) {
      console.log("初始化历史err", error);
    }
  }, []);
  const fetchHotInfo = async () => {
    let topicRes = await reqHotTopicList();
    let searchRes = await reqHotSearchList();
    let singerRes = await reqHotSingerList();
    setTopicList(topicRes.data.hot);
    setSearchList(searchRes.data.data);
    setSingerList(singerRes.data.artists);
  };
  const search = (keywords: string) => {
    try {
      let arr = Taro.getStorageSync("history") || [];
      arr = [...new Set([...arr, keywords])];
      console.log(Taro.getStorageSync("history"), "搜索数组");
      Taro.setStorageSync("history", arr);
      setHistorySearch(arr);
    } catch (error) {
      console.log("设置存储出错", error);
    }
  };
  const clearHistory = () => {
    Taro.removeStorageSync("history");
    setHistorySearch([]);
  };
  const changeTab = value => {
    setCurrentTab(value);
    console.log(value);
    if (value === 1) {
      Taro.navigateTo({
        url: "/pages/packageA/singerList/index"
      });
    }
  };
  const clickItemHandler = (keyword: string) => {
    // setKeywords(keyword);
    // fetchSearchSuggest(keyword);
    search(keyword);
    Taro.navigateTo({
      url: "/pages/packageA/searchDetailInfo/index?keyword=" + keyword
    });
  };
  const changekeyword = debounce(value => {
    setKeywords(value);
    fetchSearchSuggest(value);
  }, 400);
  const fetchSearchSuggest = async (value: string) => {
    let res = await reqSearchSuggest(value);
    if (res.data.code === 200) {
      let obj: { searchInfo: any } = {
        searchInfo: {}
      };
      obj.searchInfo = res.data.result;
      setSerchRecommend(obj);
    }
  };
  const clickSearchItem = item => {
    console.log(item);
    search(item.name);
  };
  const clickTag = (history: string) => {
    setKeywords(history);
    fetchSearchSuggest(history);
  };
  return (
    <View id="search-container-unique">
      <AtSearchBar
        actionName="搜一下"
        value={keywords}
        onChange={value => {
          changekeyword(value);
        }}
        onClear={() => {
          setKeywords("");
        }}
        onActionClick={() => {
          search(keywords);
        }}
      />
      {keywords.trim() ? (
        <SearchRecommend
          searchInfo={serchRecommend.searchInfo}
          clickItem={clickSearchItem}
        ></SearchRecommend>
      ) : (
        true
      )}
      <AtTabBar
        selectedColor="#ff0000"
        tabList={[
          { title: "单曲", iconType: "sound" },
          { title: "歌手", iconType: "user" }
        ]}
        current={currentTab}
        onClick={value => {
          changeTab(value);
        }}
      />
      {HistorySearch.length ? (
        <View className="history-search-container">
          <View className="header">
            <View className="title">历史</View>
            <AtIcon value="trash" onClick={clearHistory}></AtIcon>
          </View>
          <View className="history-tags">
            {HistorySearch &&
              HistorySearch.map((item, index) => {
                return (
                  <AtTag
                    circle
                    key={index}
                    onClick={() => {
                      clickTag(item);
                    }}
                  >
                    {item}
                  </AtTag>
                );
              })}
          </View>
        </View>
      ) : (
        true
      )}

      <ScrollView scrollX className="hot-rank-container scroll-view_x">
        <RankCard
          title="热搜榜"
          itemList={searchList}
          onClick={keyword => {
            clickItemHandler(keyword);
          }}
        ></RankCard>
        <RankCard
          title="话题榜"
          itemList={topicList}
          onClick={keyword => {
            clickItemHandler(keyword);
          }}
        ></RankCard>
        <RankCard
          title="歌手榜"
          itemList={singerList}
          onClick={keyword => {
            clickItemHandler(keyword);
          }}
        ></RankCard>
      </ScrollView>
    </View>
  );
}
